<?php

namespace Api\Model;

class SmsModel extends BaseModel {

    public function sendSMScode($phone, $datas, $tempId, $smsType) {
        $smsConfigM = M('sms_config');
        $smsConfig = $smsConfigM->where(array('tag' => 'sms_code_config'))->find();
        
        $accountSid = $smsConfig['accountSid'];
        $accountToken = $smsConfig['accountToken'];
        $appId = $smsConfig['appId'];
        $tempId = $smsConfig[$tempId];
        $serverIP = 'sandboxapp.cloopen.com';
        $serverPort = '8883';
        $softVersion = '2013-12-26';
        
        vendor('SmsSDK.CCPRestSmsSDK');
        
        $sms = new \CCPRestSmsSDK($serverIP, $serverPort, $softVersion);
        $sms->setAccount($accountSid, $accountToken);
        $sms->setAppId($appId);
        $result = $sms->sendTemplateSMS($phone, $datas, $tempId);
        
        $rt = array('status' => 1);
        if ($result == NULL) {
            $rt['status'] = -1;
            $rt['msg'] = '验证码发送错误!';
        }
        if ($result->statusCode != 0) {
            $rt['status'] = 0;
            $rt['msg'] = (string)$result->statusMsg;
            $rt['statusCode'] = (string)$result->statusCode;
            
            $data = array();
            $smsModel = M('sms_code');
            $data['smsReturnCode'] = $rt['statusCode'];
            $data['smsReturnMsg'] = $rt['msg'];
            $data['smsPhone'] = $phone;
            $data['smsType'] = $smsType;
            $data['time'] = time();
            $data['smsCode'] = $datas[0];
            $data['smsTemplateId'] = $tempId;
            $smsModel->add($data);
            unset($data);
        } else {
            $rt['status'] = 1;
            $rt['msg'] = '验证码发送成功!';
            $rt['dateCreated'] = (string)$result->TemplateSMS->dateCreated;
            $rt['smsMessageSid'] = (string)$result->TemplateSMS->smsMessageSid;
            
            $data = array();
            $smsModel = M('sms_code');
            $data['smsMessageSid'] = $rt['dateCreated'];
            $data['dateCreated'] = $rt['dateCreated'];
            $data['smsPhone'] = $phone;
            $data['smsType'] = $smsType;
            $data['time'] = time();
            $data['smsCode'] = $datas[0];
            $data['smsTemplateId'] = $tempId;
            $smsModel->add($data);
            unset($data);
        }
        return $rt;
    }

}
